package com.example.businesscalender;

import java.util.Calendar;

import com.example.database.DataBaseAdapter;
import com.example.database.Event;


import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
//import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

public class AddEvent extends Activity {
	private TextView mDateDisplay;
    private TextView mPickDate;
    private TextView mTimeDisplay;
    private TextView mPickTime;
    private int mYear;
    private int mMonth;
    private int mDay;
    private int mHour;
    private int mMinute;
    private Long mRowId;
    private DataBaseAdapter mDbHelper;
    private Event myevent = null;
    
    static final String[] PLACES = new String[] {"Nellore","Ongole","Cuddapah","Karim Nagar","Kurnool","West Godavari","Srikakulam","Anantpur","Adilabad","Chittor","east Godavari","Guntur","Hyderabad","Khammam","Krishna","Mehboobnagar","Medak","Nalgonda","Nizamabad","Prakasam","Ranga Reddy","Vishakapatnam","Vizianagaram","Warangal",
    	"Karimganj","Darrang","Dibrugarh","Morigaon","Tinsukia","Bongaigaon","Nalbari","Kokrajhar","Kamrup","Karbi-Anglong","Nagaon","N.C.Hills","Dhemaji","Hailakandi","Lakhimpur","Sonitpur","Dhubri","Goalpara","Barpeta","Golaghat","Jorhat","Sibsagar","Cachar","Jehanabad","Gaya","Patna","Saran(Chapra)",
    	"Darbhanga","Saharsa","Purnea","Bhagalpur","Munger","Aurangabad","Bhojpur(Arah)","Begusarai","EastChamparan","Gopalganj","Jamui","Katihar","Khagaria","Madhepura","Madhubani","Nalanda","Nawada","Rohtas(Sasaram) ","Samastipur","Sitamarhi","Siwan","Vaishali(Hajipur) ","WestChamparan","Kishanganj","Araria"," Bhabua","Banka","Buxar","Supaul","Sekhpura","Seohar","Lakhisarai",
    	"Panchmahals","Vadodara","Amrela","Kheda","Ahmedabad","Valsad","Junagadh","Mehsana","Banaskantha","Gandhinagar","Bharuch","Dangs","Jamnagar","Rajkot","Surat","Sabarkantha","Kutch","Bhavnagar","Surendranagar","Navsari","Anand","Narmada","Patan","Porbander","Dahod",
    	"Gurgaon","Rohtak","Ambala","Bhiwani","Faridabad","Hissar","Jind","Kaithal","Karnal","Kurukshetra","Mahendragarh","Panchkula","Panipat","Sonipat","Yamunanagar","Sirsa","Rewari","Jhanjhar","Fatehabad",
    	"Sirmour","Hamirpur","Kullu","Solan","Mandi","Chamba","Bilaspur","Kangra","Kinnaur","Lahaul-Spiti","Shimla","Una",
    	"Kathua","Badgan","Poonch","Rajauri","Baramula","Doda","Udhampur","Jammu","Kupwara","Pulwama","Anantnag","Srinagar","Leh","Kargil",
    	"Mysore","Gulberga","Chitradurga","Kolar","Bijapur","Dakshina","Kannada","Raichur","Bellary","Belgaum","Hassan","Dharwad","Bangalore","Rural","Shimoga","Mandya","Chickmagalur","Bangalore","Urban","Madikeri","Tumkur","Bidar","Karwar","Udupi","Davanagare","Chamrajnagar","Koppal","Haveri","Gadak","Yadgir",
    	"Kozhikode","Kasaragod","Idukki","Ernakulam","Cannanore","Mallapuram","Palghat","Pathanamthitta","Quilon","Trichur","Wayanad","Trivandrum","Kottayam","Alapuzzha",
    	"Sindi","Vidisha","Jabalpur","Bhopal","Hoshangabad","Indore","Rewa","Satna","Shahdol","Chhindwara","Ratlam","Balaghat","Betul","Bhind","Mandla","Chhattarpur","Damoh","Datia","Dewas","Dhar","Guna","Gwalior","Jhabua","Sehore","Mandsaur","Narsinghpur","Panna","Raisen","Rajgarh","Sagar","Seoni","Morena","Shivpuri","Shajapur","Tikamgarh","Ujjain","Khandwa","Khargone","Dindori","Umaria","Badwani","Sheopur","Katni","Neemuch","Harda","Anooppur","Burhanpur","Ashoknagar",
    	"Aurangabad","Bandra(Mumbai","Suburban","district)","Nagpur","Pune","Akola","Chandrapur","Jalgaon","Parbhani","Sholapur","Thane","Latur","Mumbai-City","Buldhana","Dhule","Kolhpur","Nanded","Raigad","Amravati","Nashik","Wardha","Ahmednagar","Beed","Bhandara","Gadchiroli","Jalna","Osmanabad","Ratnagiri","Sangli","Satara","Sindudurg","Yavatmal","Nandurbar","Washim","Gondia","Hingoli",
    	"Ri-Bhoi District","South Garo Hills","East Khasi Hill","East Garo Hill","West Garo Hill","Jaintia Hill","West Khasi","Hill Luglei District","Chimtipui District","Aizawal","Champhai","Mamit","Kolasib","Serchhip","LawngtlaiWokha","Phek","Tuensang","Mon","Kohima","Zunheboto","Mokokchung","DimapurKhurda","Navaragpur","Navapada","Gajapati","Boudh","Bhadrak","Ganjam","Dhenkanal","Angul","Puri","Cuttak","Sambalpur","Kalhandi","Koraput","Phulbani","Balangir","Bargah",
    	"Deogarh","Jagatsinghpur","Jajpur","Jharsuguda","Kendrapara","Malkangiri","Nayagarh","Rayagada","Sonepur","Balasore","Mayurbhanj","Keonjhar","Sundergarh","Sangrur","Jalandhar","Ludhiana","Bhatinda","Kapurthala","Patiala","Amritsar","Ferozepur","Fatehgarh Saheb","Ropar","Gurdaspur","Hosiarpur","Faridkot","Mansa","Moga","Muktsar","NavansaharJaipur","Barmer","Dungarpur","Jodhpur","Kota","Udaipur","Bikaner","Dausa","Bundi","Sikar","Tonk","Jaisalmer","Nagaur",
    	"Rajsamand","Banswara","Bhilwara","Ajmer","Alwar","Bharatpur","Chittorgarh","Churu","Dholpur","Ganganagar","Jalor","Jhalawar","Jhunjhunu","Pali","Sawai  Madhopur","Sirohi","Baran","Hanumangarh","Karauli","East","South","West","North","Chennai","Coimbotore","Cuddalorei","Dharmapuri","Dindigul","Erode","Kancheepuram","Kanniyakumari (HQ : Nagercoil)","Karur","Madurai","Nagapattinam","Namakkal","Nilgiris (HQ : Udhagamandalam)","Perambalur","Pudukkottai",
    	"Ramanathapuram","Salem","Sivaganga","Thanjavur","Theni","Thoothkudi","Tiruchiorappalli","Tirunelveli","Tiruvallur","Tiruvannamalai","Tiruvarur","Vellore","Villupuram","Virudhunagar","North District","South District","West District","Dhalai District","Allahabad","Aligarh","Bareilly","Gonda","Hardoi","Kanpur","Dehat","Ghaziabad","Unnav","Varanasi","Faizabad","Gorakpur","Jhansi","Lucknow","Agra","Meerut","Moradabad","Barabanki","Mainpuri","Etawah","Gazipur",
    	"Etah","Muzaffar Nagar","Saharanpur","Bulandshehar","Mathura","Firozabad","Budaun","Shahjahanpur","Pilibhit","Bijnor","Rampur","Kanpur(Nagar)","Farrukhabad","Fatehpur","Pratapgarh","Jalaun","Hamirpur","Lalitpur","Mirzapur","Basti","Deoria","Raebareili","Sitapur","Banda","Lakhimpur-Khedi","Bahraich","Sultanpur","Mau","Azamgarh","Jaunpur","Balia","Bhadoi","Padrauna","Maharajganj","Siddharth Nagar","Sunbhadra","Mahoba","Ambedkarnagar","Gautam Bodda Nagar",
    	"Maha Maya Nagar","jyotiba Phoole Nagar","Kaushambi","Shooji Maharaj","Chandauli","Balrampur","Shravati","Bagpat","Kanooj","Oraiyya","Sant Kabir Nagar","Howrah","Darjeeling","Medinipur","Murshidabad","Coochbehar","Malda","Birbhum","North 24 Parganas","South 24 Parganas","Bankura","Bardhaman","Jalpaiguri","Hooghly","Nadia","Dakshin Dinajpur","Purulia","Uttar Dinajpur","Siliguri","New Delhi","Central","North","North West","West","South West","North",
    	"North East","North Goa","South Goa","Karikal","Mahe","Yaman","Pondicherry","Lakshdweep","Dama","Diu","DadraChandigarh","Andaman","Nicobar","Nainital","Almora","Pitoragarh","Udhamsingh Nagar","Bageshwar","Champawat","Garhwal(Pauri)","Tehri-Garhwal","Chamoli(Gopeshwar)","Uttarkashi","Dehradun","Rudraprayag","Haridwar","Deoghar","Dhanbad","Giridih","Godda","Gumla","Hazaribagh","Lohardaga","Palamu","Ranchi","Dumka","Chaibasa(West Singhbhum)",
    	"Jamshedpur(East Singhbhum)","Bokaro","Chatra","Garhwa","Koderma","Pakur","Sahebganj","Simdega","Latehar","Saraikela","JamtaraBastar","Bilaspur","Dantewada","Dhamtari","Durg","Janjgir-Champa","Jashpur","Kanker","Kawardha","Korba","Koriya","Mahasamund","Raigarh","Rajnandgaon","Surguja","Raipur"
    };
    static final int TIME_DIALOG_ID = 0;
    static final int DATE_DIALOG_ID = 1;
    
    Button save;
    Spinner cat_list;
    Spinner prio_list;
    AutoCompleteTextView textView;
    EditText about;
    
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mDbHelper = new DataBaseAdapter(this);
        mDbHelper.open();
        setContentView(R.layout.addevent);
        
        about=(EditText)this.findViewById(R.id.about);
        //category select items
        cat_list = (Spinner) findViewById(R.id.categoryselect);
        ArrayAdapter<CharSequence> adapter1 = ArrayAdapter.createFromResource(
                this, R.array.category_array, android.R.layout.simple_spinner_item);
        adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        cat_list.setAdapter(adapter1);
        cat_list.setOnItemSelectedListener(new MyOnItemSelectedListener());
        //priority select items
        prio_list = (Spinner) findViewById(R.id.priorityselect);
        ArrayAdapter<CharSequence> adapter2 = ArrayAdapter.createFromResource(
                this, R.array.priority_array, android.R.layout.simple_spinner_item);
        adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        prio_list.setAdapter(adapter2);
        prio_list.setOnItemSelectedListener(new MyOnItemSelectedListener());
     // capture our View elements
        mDateDisplay = (TextView) findViewById(R.id.pickDate);
        mPickDate = (TextView) findViewById(R.id.pickDate);

        // add a click listener to the button
        mPickDate.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                showDialog(DATE_DIALOG_ID);
            }
        });

        // get the current date
        final Calendar d = Calendar.getInstance();
        mYear = d.get(Calendar.YEAR);
        mMonth = d.get(Calendar.MONTH);
        mDay = d.get(Calendar.DAY_OF_MONTH);

        // display the current date (this method is below)
        updateDate();
        
     // capture our View elements
        mTimeDisplay = (TextView) findViewById(R.id.pickTime);
        mPickTime = (TextView) findViewById(R.id.pickTime);

        // add a click listener to the button
        mPickTime.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                showDialog(TIME_DIALOG_ID);
            }
        });

        // get the current time
        final Calendar t = Calendar.getInstance();
        mHour = t.get(Calendar.HOUR_OF_DAY);
        mMinute = t.get(Calendar.MINUTE);

        // display the current date
        updateTime();
        //place picker auto complete
        textView = (AutoCompleteTextView) findViewById(R.id.autocomplete_place);
        ArrayAdapter<String> place_adapter = new ArrayAdapter<String>(this, R.drawable.list_item, PLACES);
        textView.setAdapter(place_adapter);
        
        save=(Button)this.findViewById(R.id.save);
        
        mRowId = null;
        Bundle extras = getIntent().getExtras();
        mRowId = (savedInstanceState == null) ? null : (Long) savedInstanceState.getSerializable(DataBaseAdapter.KEY_ROWID);
        if (extras != null) {
            mRowId = extras.getLong(DataBaseAdapter.KEY_ROWID);
        }
        populateFields();
        
        save.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {

                setResult(RESULT_OK);
                finish();
            }

        });
        
        

        
	}
	private void populateFields() {

        if (mRowId != null) {
            Cursor todo = mDbHelper.fetchTodo(mRowId);
            startManagingCursor(todo);
            
            about.setText(todo.getString(todo.getColumnIndexOrThrow(DataBaseAdapter.KEY_ABOUT)));
            //cat_list.setTag(todo.getString(todo.getColumnIndexOrThrow(DataBaseAdapter.KEY_CATEGORY)));
            String category = todo.getString(todo.getColumnIndexOrThrow(DataBaseAdapter.KEY_CATEGORY));

            for (int i = 0; i < cat_list.getCount(); i++) {

                String s = (String) cat_list.getItemAtPosition(i);
                Log.e(null, s + " " + category);
                if (s.equalsIgnoreCase(category)) {
                	cat_list.setSelection(i);
                }
            }
            //prio_list.setTag(todo.getString(todo.getColumnIndexOrThrow(DataBaseAdapter.KEY_PRIORITY)));
            String priority = todo.getString(todo.getColumnIndexOrThrow(DataBaseAdapter.KEY_PRIORITY));

            for (int i = 0; i < prio_list.getCount(); i++) {

                String s = (String) prio_list.getItemAtPosition(i);
                Log.e(null, s + " " + priority);
                if (s.equalsIgnoreCase(priority)) {
                	prio_list.setSelection(i);
                }
            }
            
            mPickDate.setText(todo.getString(todo.getColumnIndexOrThrow(DataBaseAdapter.KEY_DATE)));
            
            
            mPickTime.setText(todo.getString(todo.getColumnIndexOrThrow(DataBaseAdapter.KEY_TIME)));
            textView.setText(todo.getString(todo.getColumnIndexOrThrow(DataBaseAdapter.KEY_PLACE)));
            //Toast.makeText(this, mPickDate.toString(), Toast.LENGTH_LONG).show();
        }
    }

    protected void onSaveInstanceState(Bundle outState) {

        super.onSaveInstanceState(outState);
        saveState();
        outState.putSerializable(DataBaseAdapter.KEY_ROWID, mRowId);
    }

    @Override
    protected void onPause() {

        super.onPause();
        saveState();
    }

    @Override
    protected void onResume() {

        super.onResume();
        populateFields();
    }

    private void saveState() {

        myevent = new Event();
        myevent.about = about.getText().toString();
        
        myevent.category = (String) cat_list.getSelectedItem();
        myevent.priority = (String) prio_list.getSelectedItem();
        myevent.edate= mPickDate.getText().toString();
        myevent.etime= mPickTime.getText().toString();
        myevent.place = textView.getText().toString();
        
        if (mRowId == null) {
            long id = mDbHelper.createEvent(myevent);
            if (id > 0) {
                mRowId = id;
            }
        } else {
            mDbHelper.updateEvent(mRowId, myevent);
        }
    }
	
	public void save_event(View s) {
		// TODO Auto-generated method stub
		Intent event_save=new Intent();
		event_save.setClass(this, SaveEvent.class);
		this.startActivity(event_save);
		//startActivity(new Intent("com.example.businesscalender.NEXTMENU"));
	}
	
	private void updateDate() {
		// TODO Auto-generated method stub
		mDateDisplay.setText(
	            new StringBuilder()
	                    // Month is 0 based so add 1
	                    .append(mMonth + 1).append("-")
	                    .append(mDay).append("-")
	                    .append(mYear).append(" "));
	}
	public void setmDateSetListener(DatePickerDialog.OnDateSetListener mDateSetListener) {
		this.mDateSetListener = mDateSetListener;
	}
	public DatePickerDialog.OnDateSetListener getmDateSetListener() {
		return mDateSetListener;
	}
	private DatePickerDialog.OnDateSetListener mDateSetListener =
        new DatePickerDialog.OnDateSetListener() {

            public void onDateSet(DatePicker view, int year, 
                                  int monthOfYear, int dayOfMonth) {
                mYear = year;
                mMonth = monthOfYear;
                mDay = dayOfMonth;
                updateDate();
            }
        };
        
        private void updateTime() {
    	    mTimeDisplay.setText(
    	        new StringBuilder()
    	                .append(pad(mHour)).append(":")
    	                .append(pad(mMinute)));
    	}

    	private static String pad(int c) {
    	    if (c >= 10)
    	        return String.valueOf(c);
    	    else
    	        return "0" + String.valueOf(c);
    	}
    	
    	private TimePickerDialog.OnTimeSetListener mTimeSetListener =
    	    new TimePickerDialog.OnTimeSetListener() {
    	        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
    	            mHour = hourOfDay;
    	            mMinute = minute;
    	            updateTime();
    	        }
    	    };
    	    
    	    protected Dialog onCreateDialog(int id) {
                switch (id) {
                case DATE_DIALOG_ID:
                    return new DatePickerDialog(this,
                                mDateSetListener,
                                mYear, mMonth, mDay);
                case TIME_DIALOG_ID:
    	            return new TimePickerDialog(this,
    	                    mTimeSetListener, mHour, mMinute, false);
                
                }
                return null;
            }
	
}
  class MyOnItemSelectedListener implements OnItemSelectedListener {

    public void onItemSelected(AdapterView<?> parent,View view, int pos, long id) {
      //Toast.makeText(parent.getContext(),parent.getItemAtPosition(pos).toString(), Toast.LENGTH_LONG).show();
    }

    public void onNothingSelected(AdapterView<?> parent) {
        // Do nothing.
      }
    
    
}
